package com.blockmeta.bbs.baselibrary.utils;

import android.content.Context;
import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author AirThor
 * @date 2019/6/20.
 */
public class SecurityUtil {
    private static final String AES = "AES/CBC/PKCS5Padding";

    private static final String CRYPT_KEY = "WTAHAPPYACTIVITY";

    /**
     * 加密
     */
    public static byte[] encrypt(byte[] src, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(AES);
        SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), "AES");
        // 初始化向量,在密钥相同的前提下，加上初始化向量，相同内容加密后相同
        IvParameterSpec zeroIv = new IvParameterSpec(key.getBytes());
        //设置密钥和加密形式
        cipher.init(Cipher.ENCRYPT_MODE, securekey, zeroIv);
        return cipher.doFinal(src);
    }

    /**
     * 解密
     */
    public static byte[] decrypt(byte[] src, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(AES);
        //设置加密Key
        SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), "AES");
        // 初始化向量,在密钥相同的前提下，加上初始化向量，相同内容加密后相同
        IvParameterSpec zeroIv = new IvParameterSpec(key.getBytes());
        //设置密钥和解密形式
        cipher.init(Cipher.DECRYPT_MODE, securekey, zeroIv);
        return cipher.doFinal(src);
    }

    /**
     * 二行制转十六进制字符串
     */
    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs.toUpperCase();
    }

    public static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException("长度不是偶数");
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }

    /**
     * 解密
     */
    public final static byte[] decrypt(String data) throws Exception {
        try {
            return decrypt(data.getBytes(), CRYPT_KEY);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 加密
     */
    public final static byte[] encrypt(String data) throws Exception {
        try {
            return encrypt(data.getBytes(), CRYPT_KEY);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 解密
     */
    public final static byte[] decrypt(String data, String cryptKey) throws Exception {
        try {
            return decrypt(data.getBytes(), cryptKey);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 加密
     */
    public final static byte[] encrypt(String data, String cryptKey) throws Exception {
        try {
            return encrypt(data.getBytes(), cryptKey);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * MD5加密
     *
     * @param string 需要加密的
     * @return md5
     */
    public static String MD5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String mVersion = "";

    /**
     * 获取当前版本号
     */
    public static String getVersionName(Context context) {
        if (TextUtils.isEmpty(mVersion)) {
            String versionName = "";
            try {
                versionName = context.getPackageManager().getPackageInfo(
                        context.getPackageName(), 0).versionName;

                mVersion = versionName;
            } catch (Exception e) {
            }
        }

        return mVersion;
    }

    private static final String HASH_ALGORITHM_SHA1 = "SHA-1";
    public static String sha1hash(String key) {
        return hashWithAlgorithm(HASH_ALGORITHM_SHA1, key);
    }

    public static String sha1hash(byte[] bytes) {
        return hashWithAlgorithm(HASH_ALGORITHM_SHA1, bytes);
    }

    private static String hashWithAlgorithm(String algorithm, String key) {
        return hashWithAlgorithm(algorithm, key.getBytes());
    }

    private static String hashWithAlgorithm(String algorithm, byte[] bytes) {
        MessageDigest hash;
        try {
            hash = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return hashBytes(hash, bytes);
    }

    private static String hashBytes(MessageDigest hash, byte[] bytes) {
        hash.update(bytes);
        byte[] digest = hash.digest();
        StringBuilder builder = new StringBuilder();
        for (int b : digest) {
            builder.append(Integer.toHexString((b >> 4) & 0xf));
            builder.append(Integer.toHexString((b >> 0) & 0xf));
        }
        return builder.toString();
    }
}
